package com.kingmgg.kg_base.ui

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.kingmgg.kg_base.ext.saveAs
import com.kingmgg.kg_base.ext.saveAsUnChecked
import java.lang.reflect.ParameterizedType


/**
 *    Create by 金KingMgg  kingmgg
 *    on 2023/11/17 17:56
 *    程序人员写程序，又拿程序换酒钱
 *
 */
abstract class BaseVmActivity<DB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {

    lateinit var binding: DB
    lateinit var vm: VM


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val type = javaClass.genericSuperclass
        val vbClass: Class<DB> = type!!.saveAs<ParameterizedType>().actualTypeArguments[0].saveAs()
        val method = vbClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(this, layoutInflater)!!.saveAsUnChecked()
        setContentView(binding.root)

        initVM()
        bindVM()
        ARouter.getInstance().inject(this)
        initView()
    }

    /**
     * 初始化一些数据
     */
    abstract fun initView()

    /**
     * 初始化vm
     */
    private fun initVM() {
        val argument = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
        vm = ViewModelProvider(this)[argument[1] as Class<VM>]
        vm.intoActivity(this)
    }

    /**
     * 让DataBinding与ViewModel绑定
     *
     */
    protected abstract fun bindVM()

}